$(function(){
	initFormData();
	initSubmitEvent();
	backTrade();
});

/**
 *  初始化表单数据
 */
function initFormData(){
	$("input[name=auditResult]").click(function(){
		changeTradeSettingDom(this.value);
	});
	changeTradeSettingDom($("input[name=auditResult]:checked").val());
}

function initSubmitEvent(){
	$('#submitForm').validate({
		debug: false, //调试模式取消submit的默认提交功能   
        focusInvalid: false, 
        onkeyup: false,   
        submitHandler: function(form){
            if (typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
            	jQuery.data(this, "disabledOnSubmit", {submited : true});
            	var flag = $("input[name=auditFlag]").val();
            	var tipsMessage = (flag ==="true")?"请确认是否审核通过?":"请确认是否审核不通过?";
            	if (confirm(tipsMessage)) {
            		form.submit();
            	} else {
            		jQuery.removeData(this,"disabledOnSubmit");
            	}
            } else {
            	// repeat submit ignore;
            }
        },
        success:function(element){
        },
		errorPlacement : function(error, element) {
			if(error.text()){
				if(element.next("span[class='error red']").size() == 0){
					element.after("<span class='error red'>" + error.text() +"</span>");
				}else{
					element.next("span[class='error red']").text(error.text());
				}
			}else{
				element.next("span[class='error red']").remove();
			}
		},
        rules:{
        	remark:{
        		conditionRequired:(function(){
        			var flag = $("input[name=auditFlag]").val();
        			if(flag != "true"){
        				//审核不通过，备注信息必填
        				var remark = $("[name=remark]").val();
        				remark = remark.replace(/(^\s*)|(\s*$)/g, '');//去除空格
        				if( remark == undefined || remark == "" || remark == null){
        					return true;
        				}
        			}
        			return false;
        		})
        	},
            "goods.goodsCode":{
                required:true,
                remote:{
                    url:appServer + '/goods/ajax/validateGoodsCode.json',
                    type: "post",
                    dataType: "json",
                    data:{"goodsCode":function(){return $("input[name='goods.goodsCode']").val();}}
                }
            },
            "goods.beginPrice":{required:true,isIntDigit:10},
            "goods.reservePrice":{conditionRequired:['#bidModel',['freeQuoteBid','freeBid','fixBid']],isIntDigit:10},
            "goods.priceIncrease":{required:true,isFloatGtZero:true,isIntDigit:10},
            "goods.promiseMoney":{required:true,isIntDigit2:12},
            "goods.endPrice":{
				conditionRequired:(function(){
					var bidModel = $("#bidModel").val();
					if(bidModel == 'freeQuoteBid' || bidModel == 'reducePriceBid'){
						return true;
					}else{
						return false;
					}
				}),
				isIntDigit2:12,
				isFloatGteThen:["#reservePrice"],
				customRule:(function(){
					var endPrice = $("#endPrice").val();
					var beginPrice = $("#beginPrice").val();
					var priceIncrease = $("#priceIncrease").val();
					if (endPrice) {
						return (parseFloat(endPrice) > parseFloat(beginPrice)) && (parseFloat(endPrice*100) - parseFloat(beginPrice*100)) % parseFloat(priceIncrease*100) == 0;
					}else{
						return true;
					}
				})
			},
			"goods.maxBidLimit":{
                conditionRequired:checkBidMaxLimitRequired
            },
            "goods.backTradeDelayDays":{
                conditionRequired:(function (){
					var backTradeDelayDays1 = $("#backTradeDelayDays1").val();
					if(backTradeDelayDays1!="-1"){
						return true;
					}else {
						return false;
					}
                })
			},
            "goods.promiseRadio":{conditionRequired:['#bidModel',['freeBid','fixBid']]},
            "goods.fixBuyerFee":{conditionRequired:['#bidModel',['freeQuoteBid','reducePriceBid']],isIntDigit:10},
            "goods.fixSellChange":{conditionRequired:['#bidModel',['freeQuoteBid','reducePriceBid']],isIntDigit:10},
            "goods.sellChangeConey":{conditionRequired:['#bidModel',['freeBid','fixBid']]},
            "goods.buyChangeMoney":{conditionRequired:['#bidModel',['freeBid','fixBid']]},
			"goods.beginTime":{required:true},
			"goods.endTime":{required:true}
        },
        messages:{
        	remark:{conditionRequired:"审核不通过,备注信息必填"},
        	"goods.priceIncrease":{isFloatGtZero:"请输入大于0的数字"},
        	"goods.endPrice":{
        		isFloatGteThen:"请输入大于或等于保留价的值",
        		customRule:"请输入有效的价格(加价幅度的倍数+底价)"
        	},
			"goods.goodsCode":{remote:"该编号已存在"}
        }
    });
}

function changeTradeSettingDom(flag){
	$("input[name=auditFlag]").val(flag);
	if (flag === "true") {
		$("div.tradeSettingSubmit").html($("div.tradeSetting").html());
		$("div.tradeSettingSubmit").show();
	} else {
		$("div.tradeSettingSubmit").html("");
		$("div.tradeSettingSubmit").hide();
	}
}

/**
 * 返回表单中maxBixLimit字段的必填判断
 * @returns {Boolean}
 */
function checkBidMaxLimitRequired(){
	return $("#bidModel").val() == 'freeQuoteBid' && $("select[name='maxBidLimitOption']").val() == '1';
}

//是否回拍选择
function backTrade() {
	var selectedValue = $("#backTradeDelayDays1").val();
	if(selectedValue == "-1"){
		$("#backTradeDelayDays").val('');
		$(".backTradeDelayDaysSpan").hide();
	} else {
        $(".backTradeDelayDaysSpan").show();
	}
}

function num(obj){
	obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
	obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
	obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
	obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
	if(parseFloat(obj.value)>100){
		obj.value = 100;
	}	
}
function checkvalue(obj){
	obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
	obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字
	obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
	obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数	
}
function selectRooms() {
    window.open(appServer+'/goods/platformRoom/getRooms.htm?callBack=setRooms', 'newwindow', 'height=400, width=1000, top=20,left=150, toolbar=no, menubar=no, scrollbars=yes, resizable=no,location=no, status=no').focus();
}

function setRooms(json){
    $("input[name='platformRooms.id']").val(json.roomId);
    $("input[name='platformRooms.roomName']").val(json.roomName);
}

function clearRooms(){
    $("input[name='platformRooms.id']").val("");
    $("input[name='platformRooms.roomName']").val("");
}

function changeq(q){
    var chinese=/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g;
    var atAT=/AT|at|At|aT/g;
    var space=/(^\s+)|(\s+$)/g;
    if(chinese.test(q)){
        this.value=q.replace(chinese,'');
        $("#goodsCode").val(this.value);
    }else if(atAT.test(q)){
        this.value=q.replace(atAT,'');
        $("#goodsCode").val(this.value);
    }else if(space.test(q)){
        this.value=q.replace(space,'');
        $("#goodsCode").val(this.value);
    }
}